package com.yzt.zhuju.widget.tuiview;

import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleableRes;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.graphics.drawable.DrawableCompat;

import com.yzt.p_base.AppUtils;

/**
 * author : bob
 * date   : 2022/11/29
 * desc   :
 */
public class TUIUtils {

    private TUIUtils() {
        throw new IllegalStateException();
    }

    /**
     * 获取Drawable , SVG的4.+兼容处理 , 代替{@link android.support.v7.widget.TintTypedArray}
     */
    @Nullable
    public static Drawable getTintDrawable(@NonNull TypedArray array, @StyleableRes int index) {
        int resourceId = array.getResourceId(index, -1);
        return resourceId == -1 ? null : AppCompatResources.getDrawable(AppUtils.getApp(), resourceId);
    }

    /**
     * 着色
     */
    public static Drawable tint(@Nullable Drawable drawable, @ColorInt int color) {
        if (null == drawable) {
            return null;
        }
        Drawable d = DrawableCompat.wrap(drawable.mutate());
        DrawableCompat.setTint(d, color);
        return d;
    }

    /**
     * 着色
     */
    public static Drawable tint(@Nullable Drawable drawable, @ColorInt int color, @NonNull PorterDuff.Mode mode) {
        if (null == drawable) {
            return null;
        }
        Drawable d = DrawableCompat.wrap(drawable.mutate());
        DrawableCompat.setTintMode(d, mode);
        DrawableCompat.setTint(d, color);
        return d;
    }

    /**
     * 着色，注意states顺序
     * <pre>
     *     int[][] states = new int[2][];
     *     states[0] = new int[]{android.R.attr.state_pressed};
     *     states[1] = new int[]{};
     *
     *     new int[]{
     *     ContextCompat.getColor(v.getContext(), R.color.colorAccent),
     *     ContextCompat.getColor(v.getContext(), R.color.colorPrimaryDark)
     * }));
     */
    public static Drawable tint(@Nullable Drawable drawable, @NonNull int[][] states, @NonNull int[] colors) {
        if (null == drawable) {
            return null;
        }
        if (states.length != colors.length) {
            throw new IllegalArgumentException("states length error");
        }
        StateListDrawable listDrawable = new StateListDrawable();
        ColorStateList colorStateList = new ColorStateList(states, colors);
        for (int[] state : states) {
            listDrawable.addState(state, drawable);
        }
        Drawable result = DrawableCompat.wrap(listDrawable);
        DrawableCompat.setTintList(result, colorStateList);
        return result;
    }
}
